<template>
  <el-dialog v-model="addApiDlg" title="引用接口" width="88%" :before-close="clickClear" top="0">
    <el-row :gutter="10" class="main-content">
      <!-- 左边内容 -->
      <el-col :xs="24" :sm="8" :md="6" :lg="6" :xl="5" class="left-panel">
        <treeNode @treeClick="handleTreeClick" :handleTreeClick="handleTreeClick"></treeNode>
      </el-col>
      <!-- 右边内容 -->
      <el-col :xs="24" :sm="16" :md="18" :lg="18" :xl="19" class="right-content">
        <div class="search-area">
          <el-input style="width: 100%; max-width: 300px; margin-right: 10px; margin-bottom: 10px;" v-model="filterText" placeholder="请输入接口名称进行搜索" clearable>
          </el-input>
          <el-button type="primary" @click="handlenewInterfacesClick" style="margin-bottom: 10px;">查询</el-button>
          <el-button @click="filterText=''" style="margin-bottom: 10px;">重置</el-button>
        </div>
        <div class="action-buttons">
          <div class="button-group">
            <el-button
              type="primary"
              @click="userInterface"
              style="margin-right: 10px; margin-bottom: 10px;"
                >
              <el-icon style="margin-right: 6px"><View /></el-icon>
              {{buttonText}}
            </el-button>
            <el-button
              type="primary"
              @click="dialogVisible = true"
              style="margin-right: 10px; margin-bottom: 10px;"
                >
              <el-icon style="margin-right: 6px"><Star /></el-icon>
              选择环境
            </el-button>
          </div>
          <div class="env-info">
            <span style="font-size: 14px; color: #909399; margin-right: 10px; margin-bottom: 10px; display: inline-block;">当前环境：
                <el-button
                  type="info"
                  disabled
                  plain
                  >{{ selectedEnvironmentName }}</el-button>
            </span>
            <el-button
              type="warning"
              style="margin-right: 10px; margin-bottom: 10px;"
              @click="clickClear"
                >
              <el-icon style="margin-right: 6px"><Close /></el-icon>
              关闭窗口
            </el-button>
            <el-button
              type="primary"
              style="margin-bottom: 10px;"
              @click="handleApiClick"
                >
              <el-icon style="margin-right: 6px"><Check /></el-icon>
              确认选择
            </el-button>
          </div>
        </div>
        <el-dialog v-model="dialogVisible" width="30%" title="选择环境">
          <el-form :rules="rulesinterface" ref="interfaceRef" >
            <el-form-item label="测试环境" prop="env">
              <el-select v-model.lazy="selectedEnvironment" placeholder="请选择环境" style="width: 70%;" no-data-text="暂无数据">
                <el-option v-for="item in testEnvs" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <template #footer>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmSelection">确定</el-button>
          </span>
          </template>
        </el-dialog>
        <div class="interface-title">全部接口共 ({{interfaceCount}}) 个</div>
        <el-scrollbar class="interface-scrollbar">
          <div class="interface-list">
            <div
              v-for="item in tableData"
              :key="item.id"
              class="interface-item"
              :class="[
                {'interface-item-selected': selectionConfig.selectedRowKeys.includes(item.id)},
                `method-${item.method.toLowerCase()}`
              ]"
            >
              <div class="interface-checkbox">
                <el-checkbox
                  :value="selectionConfig.selectedRowKeys.includes(item.id)"
                  @change="handleSingleSelect(item)"
                ></el-checkbox>
              </div>
              <div class="interface-content" @click="clickCopy(item.id)">
                <div class="method-section">
                  <el-tag v-if="item.method === 'POST'" color="#49cc90">{{ item.method }}</el-tag>
                  <el-tag v-if="item.method === 'GET'" color="#61affe">{{ item.method }}</el-tag>
                  <el-tag v-if="item.method === 'PUT'" color="#fca130">{{ item.method }}</el-tag>
                  <el-tag v-if="item.method === 'PATCH'" color="#50e3c2">{{ item.method }}</el-tag>
                  <el-tag v-if="item.method === 'DELETE'" color="#f93e3e">{{ item.method }}</el-tag>
                  <el-tag v-if="item.method === 'DEAD'" color="rgb(201, 233, 104)">{{ item.method }}</el-tag>
                </div>
                <div class="info-section">
                  <div class="interface-url" :title="item.url">{{ item.url }}</div>
                  <div class="interface-name" :title="item.name">{{ item.name }}</div>
                </div>
                <div class="action-section" @click.stop>
                  <el-button type="text" @click="clickEditStep(item.id)">调试</el-button>
                  <el-button type="text" @click="clickCopy(item.id)">复制</el-button>
                  <el-button type="text" @click="clickDel(item.id)">删除</el-button>
                  <el-button type="text" @click="clickLog">操作记录</el-button>
                </div>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </el-col>
    </el-row>
  </el-dialog>

  <!-- 调试测试步骤窗口 -->
  <el-drawer v-model="editCaseDlg" :destroy-on-close="true" :with-header="false" size="50%" @close="handleClose"><newEditCase ref="childRef" @closeDrawer="handleClose"  :Interface_id="Interface_id" :copyDlg="copyDlg"  style="padding: 0 10px;"></newEditCase></el-drawer>

  <!--  接口操作记录窗口-->
  <el-drawer v-model="logDlg" :with-header="false" size="50%">
    <el-card>
      <b>接口操作记录</b>
      <div style="margin-top: 10px;">
        <el-timeline>
          <el-timeline-item v-for="(activity, index) in bugLogs"
                           :key="index"
                           :timestamp="$tools.rDate(activity.create_time)"
                           placement="top"
                           color="#0bbd87">
            <el-card>
              <h4>{{ activity.handle }}</h4>
              <p v-if="activity.remark">变更记录：{{ activity.remark }}</p>
              <span style="color: #409eff;margin-right: 8px">{{ activity.update_user }}</span>
              <span>操作于 {{ $tools.rTime(activity.create_time) }}</span>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>
  </el-drawer>

  <!--  导入接口窗口-->
  <el-dialog v-model="importDlg" width="30%" title="导入接口">
    <el-form :rules="rulesinterface" ref="interfaceRef" >
    </el-form>
    <template #footer>
    <span slot="footer" class="dialog-footer">
      <el-button @click="importDlg = false">取消</el-button>
      <el-button type="primary" @click="confirmSelection1">导入</el-button>
    </span>
    </template>
  </el-dialog>
</template>

<script>
import treeNode from '../Interface/treeNode.vue';
import {ElMessage, ElMessageBox} from "element-plus";
import newEditCase from '../../components/common/InterfaceNew/neweditCase.vue';
import {mapMutations, mapState} from "vuex";
import { Check, Close, View, Star } from '@element-plus/icons-vue';

export default {
  props: {
    selectType: {
      type: String
    }
  },
  components: {
    treeNode,
    newEditCase,
    Check,
    Close,
    View,
    Star
  },
  computed: {
    buttonText() {
      return this.showOnlySelf ? '取消只看自己创建' : '只看自己创建';
    },
    ...mapState(['pro','testEnvs','envId']),
    username() {
			return window.sessionStorage.getItem('username');
		},
    env: {
			get() {
				return this.envId;
			},
			set(val) {
				this.selectEnv(val);
			}
		}
    },
  data() {
    return {
      addApiDlg:true,
      treeId: '',
      filterText:'',
      tableData: [],
      editCaseDlg: false,
      logDlg:false,
      importDlg:false,
      Interface_id: '',
      copyDlg: false,
      showOnlySelf: false,
      selectedOption:'',
      dialogVisible: false,
      selectedEnvironment: '',
      selectedEnvironmentName: '暂未选择',
      selectionConfig: {
        selectedRowKeys: [], // 已选中行的 key
        selectionChange: this.handleSelectionChange // 选择变化时的回调函数
      },
      bugLogs: [
        {
          create_time: "2024-02-18T10:30:00",
          handle: "修复了一个bug",
          remark: "这是修复bug的备注",
          update_user: "张三"
        },
        {
          create_time: "2024-02-17T14:20:00",
          handle: "重新测试了bug",
          remark: "接口名称登录变更为tms登录接口",
          update_user: "李四"
        },
        {
          create_time: "2024-02-16T09:45:00",
          handle: "提交了一个新的bug",
          update_user: "王五"
        }
      ],
      interfaceCount:0,
    };
  },
  methods: {
    ...mapMutations(['selectEnv']),
    closeModal() {
      this.$emit('close-modal');
    },
    // 点击取消
    clickClear(){
      this.closeModal()
    },

    // 处理单个选择
    handleSingleSelect(item) {
      if (this.selectType) {
          this.selectionConfig.selectedRowKeys.push(item);
      } else {
        this.selectionConfig.selectedRowKeys.push(item.id);
      }
    },

    // 把批量选择完成的数据取出id重新生成数组
    handleSelectionChange(selected) {
      if (this.selectType) {
        this.selectionConfig.selectedRowKeys = selected.map(item => item);
      }
      else {
        this.selectionConfig.selectedRowKeys = selected.map(item => item.id);
      }
    },

    // 根据接口类型展示不同的样式
    getRowClassName(row) {
      switch (row) {
        case 'GET':
          return '--el-card-border-color:#61affe'
        case 'POST':
          return '--el-card-border-color:#49cc90'
        case 'PUT':
          return '--el-card-border-color:#fca130'
        case 'DELETE':
          return '--el-card-border-color:#f93e3e'
        case 'PATCH':
          return '--el-card-border-color:#50e3c2'
        default:
          return '';
      }
    },

    // 根据对应节点展示接口信息
    async handleTreeClick(id,name,creator) {
      if(name) {
        const response = await this.$api.getNewInterfaces(id,name);
        if (response.status === 200) {
          this.treeId = id;
          this.tableData = response.data;
          this.interfaceCount = response.data.length;
        }
      } else if(creator){
        const response = await this.$api.getNewInterfaces(id,name,creator);
        if (response.status === 200) {
          this.treeId = id;
          this.tableData = response.data;
          this.interfaceCount = response.data.length;
        }
      } else {
        const response = await this.$api.getNewInterfaces(id);
        if (response.status === 200) {
          this.treeId = id;
          this.tableData = response.data;
          this.interfaceCount = response.data.length;
        }
      }
    },

    // 单个接口信息删除接口
    async delInterface(id){
      const response = await this.$api.delnewInterface(id);
			if (response.status === 204) {
        ElMessage({
          type: 'success',
          message: '删除成功',
          duration: 1000
        });
        this.handleTreeClick(this.treeId);
        this.filterText = '';
        this.selectionConfig.selectedRowKeys = [];
      }
    },

    // 确定添加
    handleApiClick(){
      if (this.selectionConfig.selectedRowKeys.length === 0) {
        ElMessage({
          type: 'warning',
          message: '请勾选数据后再操作！',
          duration: 2000
        });
        return;
      }
      const apis = [...this.selectionConfig.selectedRowKeys]
      this.$emit('childEvent', apis);
      this.filterText = '';
      this.selectionConfig.selectedRowKeys = [];
      this.clickClear()
    },

    // 点击查询
    handlenewInterfacesClick() {
      this.handleTreeClick(this.treeId,this.filterText)
    },

    // 点击删除
    clickDel(id) {
			ElMessageBox.confirm('确定要删除该接口吗?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					this.delInterface(id);
				})
				.catch(() => {
					ElMessage({
						type: 'info',
						message: '取消删除',
						duration: 1000
					});
				});
		},

    handleClose() {
      this.editCaseDlg = false;
      this.copyDlg = false;
      this.handleTreeClick(this.treeId);
    },

    clickEditStep(id) {
      this.Interface_id = id
      this.editCaseDlg = true
      this.$nextTick(() => {
        this.$refs.childRef.getInterfaceInfo(this.Interface_id);
      })
    },

    // 复制用例
		clickCopy(id) {
      this.copyDlg = true;
      this.clickEditStep(id)
    },

    // 操作记录
		clickLog() {
      this.logDlg = true;
    },

    // 只看自己创建的接口
    userInterface() {
      this.showOnlySelf = !this.showOnlySelf;
      if (this.showOnlySelf) {
        // 只看自己创建的逻辑
        this.handleTreeClick(this.treeId,'',this.username);
      } else {
        // 取消只看自己创建的逻辑
        this.handleTreeClick(this.treeId);
      }
    },

    confirmSelection() {
      this.env = this.selectedEnvironment; // 在确认选择时更新 env 数据
      this.selectedEnvironmentName = this.testEnvs.find(env => env.id === this.selectedEnvironment).name;
      this.dialogVisible = false;
    }
  }
};
</script>

<style scoped>
.main-content {
  margin: 0;
  width: 100%;
}

.left-panel {
  padding: 10px;
  height: 100%;
}

.right-content {
  padding: 10px 15px;
  background-color: #f5f7fa;
}

.search-area {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-top: 20px;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  margin: 20px 0;
}

.button-group {
  display: flex;
  flex-wrap: wrap;
}

.env-info {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.interface-title {
  clear: both;
  font-weight: 500;
  margin-top: 10px;
  margin-bottom: 15px;
  border-left: 3px solid #2395f1;
  padding-left: 10px;
  font-size: 15px;
  color: #303133;
}

.interface-scrollbar {
  height: calc(100vh - 250px);
  min-height: 400px;
}

.interface-list {
  width: 100%;
}

.interface-item {
  display: flex;
  margin-bottom: 12px;
  background: #fff;
  border-radius: 6px;
  border: 1px solid #ebeef5;
  transition: all 0.3s;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-left-width: 5px;
}

.method-get {
  border-left-color: #61affe;
}

.method-post {
  border-left-color: #49cc90;
}

.method-put {
  border-left-color: #fca130;
}

.method-delete {
  border-left-color: #f93e3e;
}

.method-patch {
  border-left-color: #50e3c2;
}

.method-dead {
  border-left-color: rgb(201, 233, 104);
}

.interface-item:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.interface-item-selected {
  border: 1px solid #409eff;
  border-left-width: 5px;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.3);
}

.interface-checkbox {
  display: flex;
  align-items: center;
  padding: 0 15px;
}

.interface-content {
  flex: 1;
  display: flex;
  padding: 18px 0;
  align-items: center;
  cursor: pointer;
  flex-wrap: wrap;
}

.method-section {
  width: 90px;
  display: flex;
  justify-content: center;
  padding: 0 10px;
  margin: 5px 0;
}

.info-section {
  flex: 1;
  padding: 0 15px;
  min-width: 200px;
  overflow: hidden;
  margin: 5px 0;
}

.interface-url {
  font-weight: bold;
  font-size: 15px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 8px;
  color: #303133;
}

.interface-name {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.action-section {
  width: 100%;
  max-width: 300px;
  display: flex;
  flex-wrap: wrap;
  padding: 0 15px;
  margin: 5px 0;
}

.action-section .el-button {
  margin: 3px 8px;
  font-size: 13px;
}

.el-tag {
  color: #ffffff;
  width: 70px;
  height: 30px;
  text-align: center;
  font-size: 14px;
  line-height: 30px;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .interface-content {
    flex-direction: column;
    align-items: flex-start;
    padding: 10px 0;
  }

  .method-section, .info-section, .action-section {
    width: 100%;
    justify-content: flex-start;
    padding: 5px 15px;
  }

  .info-section {
    order: -1;
  }

  .action-section {
    max-width: 100%;
  }

  .interface-scrollbar {
    height: calc(100vh - 350px);
  }

  .el-tag {
    margin-bottom: 5px;
  }
}
</style>
